package com.xl.rentkeeper.act;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xl.fuse.protos.account.User;
import com.xl.fuse.protos.app.UpgradeInfo;
import com.xl.fuse.protos.viewroom.ViewOrderStatus;
import com.xl.rentkeeper.R;
import com.xl.rentkeeper.act.kanfang.AddLookRoomInfoAct;
import com.xl.rentkeeper.business.OrderLogic;
import com.xl.rentkeeper.business.UpdateLogic;
import com.xl.rentkeeper.business.UserLogic;
import com.xl.rentkeeper.entity.Order;
import com.xl.rentkeeper.fragment.JiluFragment;
import com.xl.rentkeeper.fragment.KanfangFragment;
import com.xl.rentkeeper.fragment.PendingFragment;
import com.xl.rentkeeper.fragment.SettingFragment;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.util.DialogUtil;
import com.xl.rentkeeper.util.Util;
import com.xl.rentkeeper.view.TitleBar;
import com.xl.rentkeeper.web.WebEntry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * update by Jerry on 2015/7/13.
 */
public class MainActivity extends BaseAct implements ViewPager.OnPageChangeListener, View.OnClickListener, TitleBar.IconOnClickListener {

    private static final String TAG = "MainActivity";
    String UPDATE_SERVERAPK = "RentkeeperApp.apk";

    private ViewPager mPager;
    private TextView mTVMsgCount;
    private Dialog dialog;

    private RelativeLayout mXiaoluo;
    private RelativeLayout mContact;
    private RelativeLayout mRLMe;
    private RelativeLayout mRLSetting;
    private MainPagerAdapter mAdapter;
    private List<Fragment> mFList;
    private PendingFragment pendingFragment;
    private TitleBar mTitleBar;
    private User user;
    private int page = 1;


    int[] ids = {R.id.re_xiaoluo, R.id.re_contact_list, R.id.re_me, R.id.re_setting};


    //设置默认选中的按钮
    private int mCurrentTab = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //设置不显示title
        super.onCreate(savedInstanceState);
        if (UserLogic.getInstance().getUid() <= 0) {
            finish();
            Intent intent = new Intent(this, LoginAct.class);
            startActivity(intent);
            return;
        }
        setContentView(R.layout.activity_main);

        mTitleBar = (TitleBar) findViewById(R.id.tb_main);
        setTranslucentStatus();
        initTitleBar(mTitleBar);
        mTitleBar.setLogoVisibility(View.INVISIBLE);
        initView();

        user = UserLogic.getInstance().getUser();

    }

    @Override
    public String[] monitorEvents() {
        return new String[]{OrderLogic.CMD_PROCESSING_ORDER_STATUS_UPDATE, CMD_CHECK_UPDATE};
    }

    @Override
    public void onEvent(String event, boolean ret, String errInfo, Object[] data) {
        super.onEvent(event, ret, errInfo, data);
        if (OrderLogic.CMD_PROCESSING_ORDER_STATUS_UPDATE.equals(event)) {
            QLog.d(this, "CMD_PROCESSING_ORDER_STATUS_UPDATE");
            setReceiveMsgCount();
        } else if (CMD_CHECK_UPDATE.equals(event)) {
            showUpdateInfo();
        }
    }

    public void showUpdateInfo() {

        UpgradeInfo info = UpdateLogic.getInstance().getUpgradeInfo();
        String localVersionName = Util.getPackageInfo(MainActivity.this).versionName;

        if (info != null || localVersionName.equals(info.newVer)) {
            String newVer = info.newVer;
            String newFeature = info.newFeature;
            final String downUrl = info.downUrl;

            String msg = "最新版本:" + newVer;

            DialogUtil.showMsgInfoDialog(this, new DialogUtil.DismissClickListener() {
                @Override
                public void okClick() {
                    dialog = DialogUtil.showProgressDialog(MainActivity.this, R.string.downloading);
                    dialog.setTitle("正在下载");

                    downFile(downUrl);
                }

                @Override
                public void cancelClick() {

                }
            }, msg, "更新", "确定", "取消");
        }else {
            DialogUtil.showMsgInfoDialog(this, new DialogUtil.DismissClickListener() {
                @Override
                public void okClick() {

                }

                @Override
                public void cancelClick() {

                }
            }, "当前版本已经是最新版本", "更新", "确定", "取消");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        page = intent.getIntExtra("page", -1);
        if (page == 1) {
            mPager.setCurrentItem(1);
        }
    }

    protected void initView() {


        mPager = (ViewPager) findViewById(R.id.main_pager);
        mXiaoluo = (RelativeLayout) findViewById(R.id.re_xiaoluo);
        mContact = (RelativeLayout) findViewById(R.id.re_contact_list);
        mRLMe = (RelativeLayout) findViewById(R.id.re_me);
        mRLSetting = (RelativeLayout) findViewById(R.id.re_setting);
        mTVMsgCount = (TextView) findViewById(R.id.tv_msg_number);

        //给menu_tab设置监听事件
        mXiaoluo.setSelected(true);
        mXiaoluo.setOnClickListener(this);
        mContact.setOnClickListener(this);
        mRLMe.setOnClickListener(this);
        mRLSetting.setOnClickListener(this);
        //设置小螺为默认选中项

        mFList = new ArrayList<Fragment>();
        pendingFragment = new PendingFragment();
        mFList.add(pendingFragment);
        mFList.add(new KanfangFragment());
        mFList.add(new JiluFragment());
        mFList.add(new SettingFragment());

        mAdapter = new MainPagerAdapter(getSupportFragmentManager(), mFList);
        mPager.setAdapter(mAdapter);

        // ViewPager加载数据
        mPager.setOnPageChangeListener(this);

    }

    public void setReceiveMsgCount() {
        List<Order> notReceiveList = OrderLogic.getInstance().getListByStatus(ViewOrderStatus.ORDER_NOT_RECEIVE.getValue());
        if (notReceiveList.size() == 0) {
            mTVMsgCount.setVisibility(View.INVISIBLE);
        } else {
            mTVMsgCount.setVisibility(View.VISIBLE);
            mTVMsgCount.setText("" + notReceiveList.size());
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(final int position) {
        mCurrentTab = position;
        seleted(ids[position]);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 设置对应的menu_tab的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        seleted(v.getId());
        // 设置ViewPager的选中,并且没有动画
        mPager.setCurrentItem(mCurrentTab, false);
    }

    /**
     * 设置menu_tab的选中项.
     *
     * @param id, 传入对应的id
     */
    public void seleted(int id) {
        if (pendingFragment != null) {
            if (id == R.id.re_xiaoluo) {
                pendingFragment.refresh(true);
            } else {
                pendingFragment.refresh(false);
            }
        }

        switch (id) {
            //点击消息按钮
            case R.id.re_xiaoluo:
                mCurrentTab = 0;
                mXiaoluo.setSelected(true);
                mContact.setSelected(false);
                mRLMe.setSelected(false);
                mRLSetting.setSelected(false);
                mTitleBar.setLogoVisibility(View.INVISIBLE);
                mTitleBar.setTitleName(getString(R.string.main_tab1));
                mTitleBar.setIcon2Visibility(View.VISIBLE);
                mTitleBar.setIcon2Name("查看房源");
                break;
            //点击联系人按钮
            case R.id.re_contact_list:
                mCurrentTab = 1;
                mXiaoluo.setSelected(false);
                mContact.setSelected(true);
                mRLMe.setSelected(false);
                mRLSetting.setSelected(false);
                mTitleBar.setLogoVisibility(View.VISIBLE);
                mTitleBar.setTitleName(getString(R.string.peedingview));
                mTitleBar.setIcon2Visibility(View.VISIBLE);
                mTitleBar.setIcon2Name("查看房源");
                break;
            //点击发现按钮
            case R.id.re_me:
                mCurrentTab = 2;
                mXiaoluo.setSelected(false);
                mContact.setSelected(false);
                mRLMe.setSelected(true);
                mRLSetting.setSelected(false);
                mTitleBar.setLogoVisibility(View.INVISIBLE);
                mTitleBar.setTitleName(getString(R.string.workrecord));
                mTitleBar.setIcon2Visibility(View.VISIBLE);
                mTitleBar.setIcon2Visibility(View.INVISIBLE);
               // mTitleBar.setIcon2Name("添加签约");
                break;
            //点击我按钮
            case R.id.re_setting:
                mCurrentTab = 3;
                mXiaoluo.setSelected(false);
                mContact.setSelected(false);
                mRLMe.setSelected(false);
                mRLSetting.setSelected(true);
                mTitleBar.setTitleName(getString(R.string.setting));
                mTitleBar.setLogoVisibility(View.INVISIBLE);
                mTitleBar.setIcon2Visibility(View.INVISIBLE);
                break;

            default:
                break;
        }
    }

    public class MainPagerAdapter extends PagerAdapter {
        private List<Fragment> fragments; // 每个Fragment对应一个Page
        private FragmentManager fragmentManager;


        public MainPagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments) {
            this.fragments = fragments;
            this.fragmentManager = fragmentManager;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(fragments.get(position).getView()); // 移出viewpager两边之外的page布局
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = fragments.get(position);
            if (!fragment.isAdded()) { // 如果fragment还没有added
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(fragment, fragment.getClass().getSimpleName());
                ft.commit();
                /**
                 * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
                 * 会在进程的主线程中，用异步的方式来执行。
                 * 如果想要立即执行这个等待中的操作，就要调用这个方法（只能在主线程中调用）。
                 * 要注意的是，所有的回调和相关的行为都会在这个调用中被执行完成，因此要仔细确认这个方法的调用位置。
                 */
                fragmentManager.executePendingTransactions();
            }
            if (fragment.getView().getParent() == null) {
                container.addView(fragment.getView()); // 为viewpager增加布局
            }
            return fragment.getView();
        }
    }

    @Override
    public void backClick() {
        Intent intent = new Intent(this, AddLookRoomInfoAct.class);
        startActivity(intent);
        overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
    }

    @Override
    public boolean onBack(int keyCode, KeyEvent event) {
        finish();
        return false;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (pendingFragment != null) {
            pendingFragment.refresh(mCurrentTab == 0);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        pendingFragment.refresh(false);
    }

    @Override
    public void icon2Click() {
        if (mCurrentTab == 0 || mCurrentTab == 1) {
            Intent intent = new Intent(this, WebEntry.class);
            intent.putExtra(WebEntry.Param_Url, "http://180.150.186.187/show/public/Room/list?src=preview&uin="+ user.uin);
            startActivity(intent);
        } else if (mCurrentTab == 2) {
        }
    }


    /**
     * 下载apk
     */
    public void downFile(final String url) {
        dialog.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] b = new byte[1024];
                        int charb = -1;
                        int count = 0;
                        while ((charb = is.read(b)) != -1) {
                            fileOutputStream.write(b, 0, charb);
                            count += charb;
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    closeDownDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            dialog.cancel();
            install();
        }
    };

    /**
     * 下载完成，通过handler将下载对话框取消
     */
    public void closeDownDialog() {
        new Thread() {
            public void run() {
                Message message = handler.obtainMessage();
                handler.sendMessage(message);
            }
        }.start();
    }

    /**
     * 安装应用
     */
    public void install() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK))
                , "application/vnd.android.package-archive");
        startActivity(intent);
    }


}
